@{
    ViewData["Title"] = "客户订单管理";
    Layout = null;
}

<link rel="stylesheet" href="~/layui/css/layui.css">

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3>客户订单管理</h3>
        </div>
        <div class="layui-card-body">
            <!-- 搜索区域 -->
            <div class="layui-form layui-form-pane" style="margin-bottom: 15px;">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">订单编码</label>
                        <div class="layui-input-inline">
                            <input type="text" id="search-orderCode" placeholder="请输入订单编码" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">客户名称</label>
                        <div class="layui-input-inline">
                            <input type="text" id="search-customerName" placeholder="请输入客户名称" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">订单状态</label>
                        <div class="layui-input-inline">
                            <select id="search-orderStatus" class="layui-input">
                                <option value="">全部状态</option>
                                <option value="0">草稿</option>
                                <option value="1">已生成生产工单</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn" id="btn-search">搜索</button>
                        <button class="layui-btn layui-btn-primary" id="btn-reset">重置</button>
                    </div>
                </div>
            </div>

            <!-- 工具栏 -->
            <div class="layui-btn-group" style="margin-bottom: 15px;">
                <button class="layui-btn" id="btn-add">新增</button>
                <button class="layui-btn layui-btn-danger" id="btn-delete">删除</button>
                <button class="layui-btn layui-btn-normal" id="btn-export">导出</button>
            </div>

            <!-- 数据表格 -->
            <table id="customerOrderTable" lay-filter="customerOrderTable"></table>
        </div>
    </div>
</div>

<script src="~/layui/layui.js"></script>

<script type="text/html" id="orderStatusTpl">
    {{# if(d.orderStatus == 0) { }}
        <span class="layui-badge layui-bg-gray">草稿</span>
    {{# } else if(d.orderStatus == 1) { }}
        <span class="layui-badge layui-bg-green">已生成生产工单</span>
    {{# } }}
</script>

<script type="text/html" id="orderActionTpl">
    {{# if(d.orderStatus == 0) { }}
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    {{# } else { }}
        <span style="color: #999;">已生成生产工单</span>
    {{# } }}
</script>

<script>
    layui.use(['table', 'form', 'layer', 'laydate'], function(){
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var laydate = layui.laydate;
        var $ = layui.$;

        // 初始化表格
        table.render({
            elem: '#customerOrderTable',
            url: '/CustomerOrder/GetCustomerOrders',
            cols: [[
                {type: 'checkbox', width: 50},
                {field: 'orderCode', title: '订单编码', width: 150, sort: true},
                {field: 'customerName', title: '客户名称', width: 150},
                {field: 'orderDate', title: '订货日期', width: 120, templet: function(d){
                    return new Date(d.orderDate).toLocaleDateString();
                }},
                {field: 'deliveryDate', title: '交货日期', width: 120, templet: function(d){
                    return new Date(d.deliveryDate).toLocaleDateString();
                }},
                {field: 'specification', title: '规格型号', width: 150},
                {field: 'quantity', title: '订货数量', width: 100},
                {field: 'unit', title: '单位', width: 80},
                {field: 'orderStatusText', title: '订单状态', width: 120, templet: '#orderStatusTpl'},
                {field: 'qualityRequirements', title: '质量要求', width: 200},
                {title: '操作', width: 150, align: 'center', toolbar: '#orderActionTpl'}
            ]],
            page: true,
            height: 'full-220'
        });

        // 搜索
        $('#btn-search').on('click', function(){
            var orderCode = $('#search-orderCode').val();
            var customerName = $('#search-customerName').val();
            var orderStatus = $('#search-orderStatus').val();

            var where = {};
            if(orderCode) where.orderCode = orderCode;
            if(customerName) where.customerName = customerName;
            if(orderStatus !== '') where.orderStatus = parseInt(orderStatus);

            table.reload('customerOrderTable', {
                where: where,
                page: {curr: 1}
            });
        });

        // 重置
        $('#btn-reset').on('click', function(){
            $('#search-orderCode').val('');
            $('#search-customerName').val('');
            $('#search-orderStatus').val('');
            form.render('select');

            table.reload('customerOrderTable', {
                where: {},
                page: {curr: 1}
            });
        });

        // 新增
        $('#btn-add').on('click', function(){
            openOrderDialog('add');
        });

        // 批量删除
        $('#btn-delete').on('click', function(){
            var checkStatus = table.checkStatus('customerOrderTable');
            var data = checkStatus.data;

            if(data.length === 0){
                layer.msg('请选择要删除的数据');
                return;
            }

            layer.confirm('确定删除选中的数据吗？', function(index){
                layer.msg('批量删除功能待实现');
                layer.close(index);
            });
        });

        // 导出
        $('#btn-export').on('click', function(){
            var orderCode = $('#search-orderCode').val();
            var customerName = $('#search-customerName').val();
            var orderStatus = $('#search-orderStatus').val();

            var params = new URLSearchParams();
            if(orderCode) params.append('orderCode', orderCode);
            if(customerName) params.append('customerName', customerName);
            if(orderStatus !== '') params.append('orderStatus', orderStatus);

            var url = '/CustomerOrder/Export?' + params.toString();
            window.open(url, '_blank');
        });

        // 表格行工具事件
        table.on('tool(customerOrderTable)', function(obj){
            var data = obj.data;

            // 检查订单状态，已生成生产工单的订单不允许编辑和删除
            if(data.orderStatus === 1) {
                layer.msg('已生成生产工单的订单不允许编辑或删除');
                return;
            }

            if(obj.event === 'edit'){
                openOrderDialog('edit', data);
            } else if(obj.event === 'del'){
                layer.confirm('确定删除这条记录吗？', function(index){
                    $.post('/CustomerOrder/DeleteCustomerOrder', {id: data.id}, function(res){
                        if(res.success){
                            layer.msg('删除成功');
                            table.reload('customerOrderTable');
                        } else {
                            layer.msg('删除失败：' + res.message);
                        }
                    });
                    layer.close(index);
                });
            }
        });

        // 打开订单对话框
        function openOrderDialog(type, data) {
            var title = type === 'add' ? '添加客户订单' : '修改客户订单';
            var isEdit = type === 'edit';

            var html = `
                <form class="layui-form" id="orderForm" style="padding: 20px;">
                    <input type="hidden" name="Id" value="${isEdit ? data.id : ''}">

                    <div class="layui-row">
                        <div class="layui-col-md6">
                                                     <div class="layui-form-item">
                                 <label class="layui-form-label"><span style="color: red;">*</span>产品编码</label>
                                 <div class="layui-input-block">
                                     <input type="text" name="ProductCode" required lay-verify="required" placeholder="请选择产品" class="layui-input" readonly value="${isEdit ? (data.productCode || '') : ''}">
                                     <i class="layui-icon layui-icon-search" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); cursor: pointer;" onclick="selectProduct()"></i>
                                 </div>
                             </div>

                             <div class="layui-form-item">
                                 <label class="layui-form-label">产品名称</label>
                                 <div class="layui-input-block">
                                     <input type="text" name="ProductName" placeholder="产品名称" class="layui-input" readonly>
                                 </div>
                             </div>

                             <div class="layui-form-item">
                                 <label class="layui-form-label">规格型号</label>
                                 <div class="layui-input-block">
                                     <input type="text" name="ProductSpec" placeholder="规格型号" class="layui-input" readonly>
                                 </div>
                             </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">产品名称</label>
                                <div class="layui-input-block">
                                    <input type="text" name="ProductName" placeholder="产品名称" class="layui-input" value="${isEdit ? (data.productName || '') : ''}">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label"><span style="color: red;">*</span>订单编码</label>
                                <div class="layui-input-block">
                                    <input type="text" name="OrderCode" required lay-verify="required" placeholder="请输入订单编码" class="layui-input" value="${isEdit ? data.orderCode : ''}">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                                                     <div class="layui-form-item">
                                 <label class="layui-form-label"><span style="color: red;">*</span>客户编码</label>
                                 <div class="layui-input-block">
                                     <input type="text" name="CustomerCode" required lay-verify="required" placeholder="请选择客户" class="layui-input" readonly value="${isEdit ? data.customerCode : ''}">
                                     <i class="layui-icon layui-icon-search" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); cursor: pointer;" onclick="selectCustomer()"></i>
                                 </div>
                             </div>
                        </div>
                    </div>

                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label"><span style="color: red;">*</span>客户名称</label>
                                <div class="layui-input-block">
                                    <input type="text" name="CustomerName" required lay-verify="required" placeholder="客户名称" class="layui-input" value="${isEdit ? data.customerName : ''}">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label"><span style="color: red;">*</span>订货日期</label>
                                <div class="layui-input-block">
                                    <input type="text" name="OrderDate" required lay-verify="required" placeholder="请选择订货日期" class="layui-input" value="${isEdit ? new Date(data.orderDate).toLocaleDateString() : ''}">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label"><span style="color: red;">*</span>交货日期</label>
                                <div class="layui-input-block">
                                    <input type="text" name="DeliveryDate" required lay-verify="required" placeholder="请选择交货日期" class="layui-input" value="${isEdit ? new Date(data.deliveryDate).toLocaleDateString() : ''}">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label"><span style="color: red;">*</span>订货数量</label>
                                <div class="layui-input-block">
                                    <input type="number" name="Quantity" required lay-verify="required|number" placeholder="请输入订货数量" class="layui-input" min="1" value="${isEdit ? data.quantity : '1'}">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label"><span style="color: red;">*</span>计量单位</label>
                                <div class="layui-input-block">
                                    <select name="Unit" required lay-verify="required" class="layui-input">
                                        <option value="">请选择</option>
                                        <option value="个" ${isEdit && data.unit === '个' ? 'selected' : ''}>个</option>
                                        <option value="件" ${isEdit && data.unit === '件' ? 'selected' : ''}>件</option>
                                        <option value="套" ${isEdit && data.unit === '套' ? 'selected' : ''}>套</option>
                                        <option value="台" ${isEdit && data.unit === '台' ? 'selected' : ''}>台</option>
                                        <option value="公斤" ${isEdit && data.unit === '公斤' ? 'selected' : ''}>公斤</option>
                                        <option value="吨" ${isEdit && data.unit === '吨' ? 'selected' : ''}>吨</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">规格型号</label>
                                <div class="layui-input-block">
                                    <input type="text" name="Specification" placeholder="请输入规格型号" class="layui-input" value="${isEdit ? (data.specification || '') : ''}">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">质量要求</label>
                        <div class="layui-input-block">
                            <textarea name="QualityRequirements" placeholder="请输入质量要求说明" class="layui-textarea">${isEdit ? (data.qualityRequirements || '') : ''}</textarea>
                        </div>
                    </div>

                    <div class="layui-form-item" style="text-align: center;">
                        <button type="submit" class="layui-btn" lay-submit lay-filter="orderSubmit">确定</button>
                        <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                    </div>
                </form>
            `;

            if(isEdit) {
                html += `
                    <div style="margin-top: 20px; border-top: 1px solid #e6e6e6; padding-top: 20px;">
                        <div class="layui-card">
                            <div class="layui-card-header">
                                <h4>物料需求</h4>
                                <button type="button" class="layui-btn layui-btn-sm" onclick="addMaterial(${data.id})" style="float: right;">新增物料</button>
                            </div>
                            <div class="layui-card-body">
                                <table id="materialTable_${data.id}" lay-filter="materialTable_${data.id}"></table>
                            </div>
                        </div>
                        <div style="text-align: center; margin-top: 20px;">
                            <button type="button" class="layui-btn layui-btn-normal" onclick="generateWorkOrder(${data.id})">生成生产工单</button>
                        </div>
                    </div>
                `;
            }

            layer.open({
                type: 1,
                title: title,
                content: html,
                area: ['80%', '90%'],
                maxmin: true,
                success: function(layero, index) {
                    form.render();

                    // 初始化日期选择器
                    laydate.render({
                        elem: 'input[name="OrderDate"]',
                        type: 'date'
                    });

                    laydate.render({
                        elem: 'input[name="DeliveryDate"]',
                        type: 'date'
                    });

                    // 如果是编辑模式，加载物料需求表格
                    if(isEdit) {
                        loadMaterialTable(data.id);
                    }

                    // 如果是新增模式，生成订单编码
                    if(!isEdit) {
                        $.get('/CustomerOrder/GenerateOrderCode', function(res){
                            if(res.success) {
                                $('input[name="OrderCode"]').val(res.code);
                            }
                        });
                    }
                }
            });
        }

        // 加载物料需求表格
        function loadMaterialTable(orderId) {
            table.render({
                elem: '#materialTable_' + orderId,
                url: '/CustomerOrder/GetOrderDetails',
                where: {customerOrderId: orderId},
                page: false,
                id: 'materialTable_' + orderId,
                cols: [[
                    {field: 'materialCode', title: '物料编码', width: 120},
                    {field: 'materialName', title: '物料名称', width: 150},
                    {field: 'num', title: '需求数量', width: 100, edit: 'text'},
                    {field: 'size', title: '规格尺寸', width: 120},
                    {field: 'unit', title: '单位', width: 80},
                    {field: 'stockQuantity', title: '库存数量', width: 100},
                    {title: '操作', width: 200, align: 'center', templet: function(d) {
                        return '<a class="layui-btn layui-btn-normal layui-btn-xs" onclick="editMaterial(' + d.id + ', ' + orderId + ')">编辑</a> ' +
                               '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteMaterial(' + d.id + ', ' + orderId + ')">删除</a>';
                    }}
                ]],
                done: function(res, curr, count) {
                    console.log('物料表格数据加载完成:', res);
                }
            });

            // 监听表格编辑事件
            table.on('edit(materialTable_' + orderId + ')', function(obj){
                var value = obj.value; // 得到修改后的值
                var data = obj.data; // 得到所在行所有键值
                var field = obj.field; // 得到字段

                // 只允许编辑需求数量
                if(field === 'num') {
                    // 验证输入值
                    if(!/^\d+$/.test(value) || parseInt(value) <= 0) {
                        layer.msg('需求数量必须是大于0的整数');
                        obj.update({
                            num: data.num // 恢复原值
                        });
                        return;
                    }

                    // 发送更新请求
                    $.post('/CustomerOrder/UpdateOrderDetail', {
                        detailId: data.id,
                        num: parseInt(value)
                    }, function(res){
                        if(res.success) {
                            layer.msg('更新成功');
                            // 更新表格数据
                            obj.update({
                                num: res.data.num
                            });
                        } else {
                            layer.msg('更新失败：' + res.message);
                            // 恢复原值
                            obj.update({
                                num: data.num
                            });
                        }
                    }).fail(function() {
                        layer.msg('更新失败：网络错误');
                        // 恢复原值
                        obj.update({
                            num: data.num
                        });
                    });
                }
            });
        }

        // 表单提交
        form.on('submit(orderSubmit)', function(data){
            var formData = data.field;
            var url = formData.Id ? '/CustomerOrder/UpdateCustomerOrder' : '/CustomerOrder/CreateCustomerOrder';

            $.post(url, formData, function(res){
                if(res.success){
                    layer.msg(formData.Id ? '修改成功' : '添加成功');
                    table.reload('customerOrderTable');

                    if(!formData.Id) {
                        // 新增成功后不关闭对话框，显示物料需求区域
                        layer.msg('订单创建成功，现在可以添加物料需求');
                        layer.closeAll();
                        openOrderDialog('edit', res.data);
                    } else {
                        layer.closeAll();
                    }
                } else {
                    layer.msg((formData.Id ? '修改' : '添加') + '失败：' + res.message);
                }
            });

            return false;
        });

        // 添加物料（全局函数）
        var materialDialogIndex = null;
        window.addMaterial = function(orderId) {
            // 获取可选择的物料列表
            $.get('/CustomerOrder/GetMaterialsForSelect', function(res){
                if(res.success && res.data.length > 0) {
                    var options = '<option value="">请选择物料</option>';
                    res.data.forEach(function(item) {
                        options += '<option value="' + item.id + '">' + item.materielCode + ' - ' + item.materielName + ' (库存:' + item.stockQuantity + ')</option>';
                    });

                    var html = `
                        <form class="layui-form" style="padding: 20px;">
                            <div class="layui-form-item">
                                <label class="layui-form-label">选择物料</label>
                                <div class="layui-input-block">
                                    <select name="MaterialId" required lay-verify="required">
                                        ${options}
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">需求数量</label>
                                <div class="layui-input-block">
                                    <input type="number" name="Num" required lay-verify="required|number" placeholder="请输入需求数量" class="layui-input" min="1" value="1">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">规格尺寸</label>
                                <div class="layui-input-block">
                                    <input type="text" name="Size" placeholder="请输入规格尺寸" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item" style="text-align: center;">
                                <button type="submit" class="layui-btn" lay-submit lay-filter="materialSubmit">确定</button>
                                <button type="button" class="layui-btn layui-btn-primary" onclick="closeMaterialDialog()">取消</button>
                            </div>
                        </form>
                    `;

                    materialDialogIndex = layer.open({
                        type: 1,
                        title: '添加物料需求',
                        content: html,
                        area: ['500px', '400px'],
                        success: function() {
                            form.render();

                            // 物料提交
                            form.on('submit(materialSubmit)', function(data){
                                var materialData = data.field;
                                materialData.CustomerOrderId = orderId;

                                $.post('/CustomerOrder/CreateOrderDetail', materialData, function(res){
                                    if(res.success) {
                                        layer.msg('添加成功');
                                        table.reload('materialTable_' + orderId);
                                        layer.close(materialDialogIndex);
                                    } else {
                                        layer.msg('添加失败：' + res.message);
                                    }
                                });

                                return false;
                            });
                        }
                    });
                } else {
                    layer.msg('没有可用的物料');
                }
            });
        };

        // 关闭物料对话框（全局函数）
        window.closeMaterialDialog = function() {
            if(materialDialogIndex) {
                layer.close(materialDialogIndex);
            }
        };

        // 编辑物料（全局函数）
        window.editMaterial = function(detailId, orderId) {
            layer.msg('请直接在表格中双击需求数量进行编辑', {icon: 1, time: 2000});
        };

        // 删除物料（全局函数）
        window.deleteMaterial = function(detailId, orderId) {
            layer.confirm('确定删除这条物料需求吗？', function(index){
                $.post('/CustomerOrder/DeleteOrderDetail', {detailId: detailId}, function(res){
                    if(res.success){
                        layer.msg('删除成功');
                        table.reload('materialTable_' + orderId);
                    } else {
                        layer.msg('删除失败：' + res.message);
                    }
                });
                layer.close(index);
            });
        };

        // 生成生产工单（全局函数）
        window.generateWorkOrder = function(orderId) {
            layer.confirm('确定生成生产工单吗？', function(index){
                $.post('/CustomerOrder/GenerateProductionOrder', {customerOrderId: orderId}, function(res){
                    if(res.success){
                        layer.msg('生产工单生成成功');
                        table.reload('customerOrderTable');
                        layer.closeAll();
                    } else {
                        layer.msg('生成失败：' + res.message);
                    }
                });
                             layer.close(index);
             });
         };

              // 选择产品（全局函数）
     window.selectProduct = function() {
         var productSelectIndex = layer.open({
             type: 1,
             title: '选择产品',
             content: '<div id="productSelectContainer"></div>',
             area: ['900px', '600px'],
             btn: ['确定', '取消'],
             yes: function(index) {
                 var checkStatus = table.checkStatus('productSelectTable');
                 var data = checkStatus.data;
                 if(data.length === 0) {
                     layer.msg('请选择一个产品');
                     return false;
                 }
                 selectProductItem(data[0]);
                 layer.close(index);
             },
             success: function() {
                 var html = `
                     <div style="padding: 20px;">
                         <!-- 搜索区域 -->
                         <div class="layui-form layui-form-pane" style="margin-bottom: 15px;">
                             <div class="layui-form-item">
                                 <div class="layui-inline">
                                     <label class="layui-form-label">关键字</label>
                                     <div class="layui-input-inline">
                                         <input type="text" id="product-search-keyword" placeholder="产品编码/名称/规格" class="layui-input">
                                     </div>
                                 </div>
                                 <div class="layui-inline">
                                     <button class="layui-btn" onclick="searchProducts()">搜索</button>
                                     <button class="layui-btn layui-btn-primary" onclick="resetProductSearch()">重置</button>
                                 </div>
                             </div>
                         </div>
                         <table id="productSelectTable" lay-filter="productSelectTable"></table>
                     </div>
                 `;
                 $('#productSelectContainer').html(html);
                 
                 // 初始化产品表格
                 table.render({
                     elem: '#productSelectTable',
                     url: '/CustomerOrder/GetProductsForSelect',
                     cols: [[
                         {type: 'radio', width: 50},
                         {field: 'materielCode', title: '产品编码', width: 150},
                         {field: 'materielName', title: '产品名称', width: 200},
                         {field: 'specifications', title: '规格型号', width: 200},
                         {field: 'unitsId', title: '单位', width: 100}
                     ]],
                     page: true,
                     height: 350,
                     done: function() {
                         // 双击选择
                         $('.layui-table-body').off('dblclick').on('dblclick', 'tr', function(){
                             var index = $(this).data('index');
                             var data = table.cache.productSelectTable[index];
                             if(data) {
                                 selectProductItem(data);
                                 layer.close(productSelectIndex);
                             }
                         });
                     }
                 });
             }
         });
     };

         // 搜索产品
         window.searchProducts = function() {
             var keyword = $('#product-search-keyword').val();
             table.reload('productSelectTable', {
                 where: { keyword: keyword },
                 page: { curr: 1 }
             });
         };

         // 重置产品搜索
         window.resetProductSearch = function() {
             $('#product-search-keyword').val('');
             table.reload('productSelectTable', {
                 where: {},
                 page: { curr: 1 }
             });
         };

              // 选择产品项
     window.selectProductItem = function(data) {
         $('input[name="ProductCode"]').val(data.materielCode);
         $('input[name="ProductName"]').val(data.materielName);
         $('input[name="ProductSpec"]').val(data.specifications);
     };

              // 选择客户（全局函数）
     window.selectCustomer = function() {
         var customerSelectIndex = layer.open({
             type: 1,
             title: '选择客户',
             content: '<div id="customerSelectContainer"></div>',
             area: ['900px', '600px'],
             btn: ['确定', '取消'],
             yes: function(index) {
                 var checkStatus = table.checkStatus('customerSelectTable');
                 var data = checkStatus.data;
                 if(data.length === 0) {
                     layer.msg('请选择一个客户');
                     return false;
                 }
                 selectCustomerItem(data[0]);
                 layer.close(index);
             },
             success: function() {
                 var html = `
                     <div style="padding: 20px;">
                         <!-- 搜索区域 -->
                         <div class="layui-form layui-form-pane" style="margin-bottom: 15px;">
                             <div class="layui-form-item">
                                 <div class="layui-inline">
                                     <label class="layui-form-label">关键字</label>
                                     <div class="layui-input-inline">
                                         <input type="text" id="customer-search-keyword" placeholder="客户编码/名称" class="layui-input">
                                     </div>
                                 </div>
                                 <div class="layui-inline">
                                     <button class="layui-btn" onclick="searchCustomers()">搜索</button>
                                     <button class="layui-btn layui-btn-primary" onclick="resetCustomerSearch()">重置</button>
                                 </div>
                             </div>
                         </div>
                         <table id="customerSelectTable" lay-filter="customerSelectTable"></table>
                     </div>
                 `;
                 $('#customerSelectContainer').html(html);
                 
                 // 初始化客户表格
                 table.render({
                     elem: '#customerSelectTable',
                     url: '/CustomerOrder/GetCustomersForSelect',
                     cols: [[
                         {type: 'radio', width: 50},
                         {field: 'customerCode', title: '客户编码', width: 150},
                         {field: 'customerName', title: '客户名称', width: 200},
                         {field: 'customerType', title: '客户类型', width: 150},
                         {field: 'customerPhone', title: '联系电话', width: 150}
                     ]],
                     page: true,
                     height: 350,
                     done: function() {
                         // 双击选择
                         $('.layui-table-body').off('dblclick').on('dblclick', 'tr', function(){
                             var index = $(this).data('index');
                             var data = table.cache.customerSelectTable[index];
                             if(data) {
                                 selectCustomerItem(data);
                                 layer.close(customerSelectIndex);
                             }
                         });
                     }
                 });
             }
         });
     };

         // 搜索客户
         window.searchCustomers = function() {
             var keyword = $('#customer-search-keyword').val();
             table.reload('customerSelectTable', {
                 where: { keyword: keyword },
                 page: { curr: 1 }
             });
         };

         // 重置客户搜索
         window.resetCustomerSearch = function() {
             $('#customer-search-keyword').val('');
             table.reload('customerSelectTable', {
                 where: {},
                 page: { curr: 1 }
             });
         };

              // 选择客户项
     window.selectCustomerItem = function(data) {
         $('input[name="CustomerCode"]').val(data.customerCode);
         $('input[name="CustomerName"]').val(data.customerName);
     };
     });
</script> 